package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.*;
import org.dromara.app.appReturn.AppDaRenInfo;
import org.dromara.app.appReturn.AppOrderInfo;
import org.dromara.app.config.AppGoEasyUtil;
import org.dromara.app.cssUtils.CssExceptionDescription;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.cssUtils.RedisServiceUtils;
import org.dromara.app.domain.*;
import org.dromara.app.domain.sys.SysSexSumReturn;
import org.dromara.app.domain.vo.SkAppUserVo;
import org.dromara.app.domain.vo.SkYueDanOrderLogVo;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkPriceLogMapper;
import org.dromara.app.mapper.SkYueDanOrderLogMapper;
import org.dromara.app.service.IBfExperienceLogService;
import org.dromara.app.service.ISkYueDanOrderLogService;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.params.AppTypeName;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkYueDanOrderBo;
import org.dromara.app.domain.vo.SkYueDanOrderVo;
import org.dromara.app.mapper.SkYueDanOrderMapper;
import org.dromara.app.service.ISkYueDanOrderService;

import java.math.BigDecimal;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 约单订单Service业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkYueDanOrderServiceImpl implements ISkYueDanOrderService {

    private final SkYueDanOrderMapper baseMapper;
    private final SkAppUserMapper skAppUserMapper;
    private final IBfExperienceLogService iBfExperienceLogService;
    private final ISkYueDanOrderLogService iSkYueDanOrderLogService;
    private final SkYueDanOrderLogMapper skYueDanOrderLogMapper;

    private final SkPriceLogMapper skPriceLogMapper;


    /**
     * 查询约单订单
     *
     * @param id 主键
     * @return 约单订单
     */
    @Override
    public SkYueDanOrderVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询约单订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 约单订单分页列表
     */
    @Override
    public TableDataInfo<SkYueDanOrderVo> queryPageList(SkYueDanOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkYueDanOrder> lqw = buildQueryWrapper(bo);
        Page<SkYueDanOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的约单订单列表
     *
     * @param bo 查询条件
     * @return 约单订单列表
     */
    @Override
    public List<SkYueDanOrderVo> queryList(SkYueDanOrderBo bo) {
        LambdaQueryWrapper<SkYueDanOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkYueDanOrder> buildQueryWrapper(SkYueDanOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        //判断是否城市代理账户
        LoginUser user = LoginHelper.getLoginUser();
        if (user.getRolePermission().contains("cityAgent")) {
            //是城市代理人
            bo.setCity(user.getCity());
        }
        LambdaQueryWrapper<SkYueDanOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), SkYueDanOrder::getTitle, bo.getTitle());
        lqw.eq(bo.getPrice() != null, SkYueDanOrder::getPrice, bo.getPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getLongTime()), SkYueDanOrder::getLongTime, bo.getLongTime());
        lqw.eq(StringUtils.isNotBlank(bo.getStartTime()), SkYueDanOrder::getStartTime, bo.getStartTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), SkYueDanOrder::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getNotes()), SkYueDanOrder::getNotes, bo.getNotes());
        lqw.eq(bo.getPayType() != null, SkYueDanOrder::getPayType, bo.getPayType());
        lqw.eq(bo.getUserId() != null, SkYueDanOrder::getUserId, bo.getUserId());
        lqw.eq(bo.getDarenUserId() != null, SkYueDanOrder::getDarenUserId, bo.getDarenUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderSn()), SkYueDanOrder::getOrderSn, bo.getOrderSn());
        lqw.like(StringUtils.isNotBlank(bo.getTypeTitle()), SkYueDanOrder::getDarenTitle, bo.getTypeTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), SkYueDanOrder::getCity, bo.getCity());
        lqw.eq(bo.getState() != null, SkYueDanOrder::getState, bo.getState());
        lqw.orderByDesc(SkYueDanOrder::getCreateTime);
        return lqw;
    }

    /**
     * 新增约单订单
     *
     * @param bo 约单订单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkYueDanOrderBo bo) {
        SkYueDanOrder add = MapstructUtils.convert(bo, SkYueDanOrder.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改约单订单
     *
     * @param bo 约单订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkYueDanOrderBo bo) {
        SkYueDanOrder update = MapstructUtils.convert(bo, SkYueDanOrder.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkYueDanOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除约单订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 创建预约下单
     *
     * @param params
     * @param req
     */
    @Override
    public SkYueDanOrder createReservationOrder(AppCreateYueDanParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = skAppUserMapper.selectById(userId);
        if (skAppUser.getUserType().longValue() == 2) {
            throw new RuntimeException("达人不可下单");
        }
        if (params.getDarenUserId() == null) {
            throw new RuntimeException("请选择达人");
        }
        //查询是否有未完成的订单
        QueryWrapper<SkYueDanOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("daren_user_id", params.getDarenUserId());
        // 设置 state 字段的查询条件 2：已接单 5：开始服务
        queryWrapper.in("state", 2,5);
        List<SkYueDanOrder> list = baseMapper.selectList(queryWrapper);
        if (list.size()>0){
            throw new RuntimeException("达人有未完成的订单，暂不可下单");
        }
        //生成订单
        SkYueDanOrder order = BeanUtil.copyProperties(params, SkYueDanOrder.class);
        order.setOrderSn(CssUtils.generateOrderNumber());
        order.setPayState(0L);
        order.setState(0L);
        order.setUserId(userId);
        order.setJiedanUserIds(order.getDarenUserId() + "");
        order.setAllPrice(new BigDecimal(order.getLongTime() * order.getPrice()));
        order.setPayPrice(params.getZhekouMoney());
        String endTime = DateUtil.format(DateUtil.offset(DateUtil.parse(order.getStartTime() + ":00", DatePattern.NORM_DATETIME_PATTERN), DateField.HOUR, order.getLongTime().intValue()), DatePattern.NORM_DATETIME_MINUTE_FORMATTER);
        order.setEndTime(endTime);
        order.setCity(skAppUser.getCity());
        baseMapper.insert(order);

         //经验值计算  end
        //添加开始时间倒计时，若是没有人接口则取消订单，支付原理退回
//        int minutes = CssUtils.jianGeDay(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN), order.getStartTime() + ":00");
        //没人接单，退款作业
//        RedisUtils.setCacheObject(RedisServiceUtils.getDaijiedantuikuan(order.getId()), order.getId(), Duration.ofMinutes(minutes));
        //完成达人订单作业
//        RedisUtils.setCacheObject(RedisServiceUtils.getDaRenWanCheng(order.getId()), order.getId(), Duration.ofMinutes(minutes));
        return order;
    }


//    public static void main(String[] args) {
//        System.out.println(DateUtil.format(DateUtil.offset(DateUtil.parse("2024-09-21 00:00:00",DatePattern.NORM_DATETIME_PATTERN),DateField.HOUR,3),DatePattern.NORM_DATETIME_PATTERN));
//    }

    /**
     * 达人订单
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppOrderInfo> pendingOrders(AppYueDanParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        List<AppOrderInfo> list = baseMapper.pendingOrders(params, userId);
        return list;
    }

    /**
     * 取消订单
     *
     */
    public SkYueDanOrder cencelOrder(SkYueDanOrder order) {
        //判断是否已接单
//        SkYueDanOrder order = baseMapper.selectById(orderId);
        if (order.getPayState().longValue()==0){
            CssExceptionDescription.errorMsg(10028);
        }
        if (order.getState().longValue()>1){
            CssExceptionDescription.errorMsg(10029);
        }
        //待接单自动取消
        if (order.getState().longValue() == 1) {
            //判断取消时间是否在下单15分钟之内
            Date end = DateUtil.offset(order.getCreateTime(),DateField.MINUTE,-15);
            Date start = new Date();
            BigDecimal price = order.getPayPrice();
            order.setRefundProportion("0");
            if (start.getTime()>end.getTime()){
                //查询退款扣除比例
                Object object = RedisUtils.getCacheMapValue(CacheNames.SYS_CONFIG,RedisServiceUtils.getTuikuanbili());
                if (object!=null){
                    order.setRefundProportion(object.toString());
                    price = order.getPayPrice().multiply(new BigDecimal(object.toString()).divide(new BigDecimal(100)));
                }
            }
            order.setRefundPrice(price);
            baseMapper.updateById(order);

            return order;
        }
        return null;
    }

    /**
     * 用户创建的达人订单
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppOrderInfo> myOrdersList(AppYueDanParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        List<AppOrderInfo> list = baseMapper.myOrdersList(params, userId);
        return list;
    }

    /**
     * 支付成功回调
     *
     * @param req
     * @return
     */
    @Override
    public void paymentCallback(HttpServletRequest req) {

        if (true) {
            //支付成功判断
            String orderId = "";
            SkYueDanOrder sk = baseMapper.selectById(orderId);
            if (sk.getPayState().longValue() == 0) {
                sk.setPayState(1L);
                sk.setPayTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
                sk.setPayOrder("");//三方支付订单号
                baseMapper.updateById(sk);

                //


            }
        }
    }

    @Override
    public SkYueDanOrder cencelUserOrder(AppDetailByIdParams params, HttpServletRequest req) {
        SkYueDanOrder skYueDanOrder = baseMapper.selectById(params.getId());
        if (CssUtils.getUserId(req).longValue() != skYueDanOrder.getUserId().longValue()) {
            CssExceptionDescription.errorMsg(10015);
        }
        if (skYueDanOrder.getState().longValue() > 1) {
            CssExceptionDescription.errorMsg(10016);
        }
        return cencelOrder(skYueDanOrder);
    }

    /**
     * 达人接单
     */
    @Override
    public void getReceivinOrders(AppDetailByIdParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkYueDanOrder skYueDanOrder = baseMapper.selectById(params.getId());
        if (userId.longValue() != skYueDanOrder.getDarenUserId().longValue()) {
            CssExceptionDescription.errorMsg(10017);
        }
        if (skYueDanOrder.getState().longValue() != 1) {
            CssExceptionDescription.errorMsg(10018);
        }
        //判断是否有时间冲突的接单 (已接单+开始服务状态的)
        List<SkYueDanOrder> list = baseMapper.selectList(
            new QueryWrapper<SkYueDanOrder>().lambda()
                .eq(SkYueDanOrder::getDarenUserId,userId)
                .ge(SkYueDanOrder::getStartTime,skYueDanOrder.getStartTime())
                .le(SkYueDanOrder::getEndTime,skYueDanOrder.getEndTime())
                .in(SkYueDanOrder::getState,"2,5".split(","))
        );
        if (list.size()>0){
            throw new RuntimeException("您有订单时间冲突，请先完成现有订单。");
        }

        skYueDanOrder.setState(2L);
        baseMapper.updateById(skYueDanOrder);
        //添加log
        iSkYueDanOrderLogService.createLog(skYueDanOrder, "达人接单成功", 4L);
        //达人接单发送短信（给用户发）
        SkAppUser xiadanuser = skAppUserMapper.selectById(skYueDanOrder.getUserId());
        SkAppUser darenuser = skAppUserMapper.selectById(skYueDanOrder.getDarenUserId());
        CssUtils.send(xiadanuser.getPhone(),"【尚客花街】温馨提示：达人："+darenuser.getNickName()+"，于"+DateUtil.format(new Date(),DatePattern.NORM_DATETIME_PATTERN)+"接单成功！祝您生活愉快！");
    }

    /**
     * 达人转单
     *
     * @param params
     * @param req
     */
    @Override
    public void getTransferOrder(AppDetailByIdParams params, HttpServletRequest req) {

        Long userId = CssUtils.getUserId(req);
        SkYueDanOrder skYueDanOrder = baseMapper.selectById(params.getId());
        if (userId.longValue() != skYueDanOrder.getDarenUserId().longValue()) {
            CssExceptionDescription.errorMsg(10017);
        }

        if (skYueDanOrder.getState().longValue() == 5 || skYueDanOrder.getState().longValue() == 3
            || skYueDanOrder.getState().longValue() == 4) {
            CssExceptionDescription.errorMsg(10018);
        }

        //判断距离开始时间是否小于2个小时，小于2个小时不允许转单
        Date endTime = DateUtil.offset(DateUtil.parse(skYueDanOrder.getStartTime()+":00",DatePattern.NORM_DATETIME_PATTERN),DateField.HOUR,skYueDanOrder.getLongTime().intValue()-2);
        Date start  = new Date();
        if(start.getTime()> endTime.getTime()){
            CssExceptionDescription.errorMsg(10025);
        }

        //查询可转单的用户信息
        if (skYueDanOrder.getJiedanUserIds() == null) {
            skYueDanOrder.setJiedanUserIds(skYueDanOrder.getDarenUserId().toString());
        }
//        类型 1:创建  2：转发  3：待接单  4：已接单  5：取消  6：完成
        //添加log
        iSkYueDanOrderLogService.createLog(skYueDanOrder, "达人操作转单", 2L);

        List<SkAppUser> list = skAppUserMapper.selectList(
            new QueryWrapper<SkAppUser>().lambda()
                .eq(SkAppUser::getUserType, 2)
                .eq(SkAppUser::getCommuting, 1)
                .notIn(SkAppUser::getId, skYueDanOrder.getJiedanUserIds().split(","))
        );
        if (list.size() == 0) {
            //取消订单
            skYueDanOrder.setState(3L);
            baseMapper.updateById(skYueDanOrder);
            //添加log
            iSkYueDanOrderLogService.createLog(skYueDanOrder, "达人操作转单无达人，取消订单", 5L);
        } else {
            skYueDanOrder.setDarenUserId(list.get(0).getId());
            skYueDanOrder.setJiedanUserIds(skYueDanOrder.getJiedanUserIds() + "," + list.get(0).getId());
            baseMapper.updateById(skYueDanOrder);
            iSkYueDanOrderLogService.createLog(skYueDanOrder, "达人转单待接单", 3L);
            //达人转单发送短信（给达人发）
            SkAppUser xiadanuser = skAppUserMapper.selectById(skYueDanOrder.getUserId());
            CssUtils.send(list.get(0).getPhone(),"【尚客花街】温馨提示：您有新订单，用户："+xiadanuser.getNickName()+"，于"+skYueDanOrder.getCreateTime()+"下单成功，请及时查看！");

        }
    }

    /**
     * 筛选的达人信息（消息模块）
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppDaRenInfo> getMessageList(AppMessageParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        params.setUserId(userId);
        if(params.getAge()==0){
            return new ArrayList<AppDaRenInfo>();
        }
        int year = DateUtil.year(new Date()) - params.getAge();
        params.setBirthday(year + "-12");
        if (params.getTag() != null && params.getTag().length > 0) {
            params.setTags(Arrays.stream(params.getTag()).toList());
        }
        if (params.getIsTc() == null || params.getIsTc().longValue() == 0) {
            params.setCity("");
        }
        List<AppDaRenInfo> list = baseMapper.getMessageList(params);
        if (list.size() > 0) {
            for (AppDaRenInfo app : list) {
                if (app.getBirthday() != null && !app.getBirthday().equals("")) {
                    if (CssUtils.isValidYearMonth(app.getBirthday())) {
                        LocalDate bir = LocalDate.parse(app.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                        Period age = Period.between(bir, LocalDate.now());
                        app.setAge(age.getYears() + "");
                    }
                }
            }
        }
        return list;
    }

    /**
     * 浏览历史20条数据
     */
    @Override
    public List<AppDaRenInfo> getBrowsingHistory(HttpServletRequest req) {
        List<AppDaRenInfo> list = baseMapper.getBrowsingHistory(CssUtils.getUserId(req));
        return list;
    }

    /**
     * 预约下单价格计算
     */
    @Override
    public BigDecimal reservationOrderPrice(String dictValue, Long vipType, HttpServletRequest req) {

        return null;
    }

    /**
     * 获取全新订单信息
     *
     * @param id
     * @return
     */
    @Override
    public SkYueDanOrderVo getNewInfo(Long id) {
        SkYueDanOrderVo vo = baseMapper.selectVoById(id);
        SkAppUserVo userVo = skAppUserMapper.selectVoById(vo.getUserId());
        SkAppUserVo drUserVo = skAppUserMapper.selectVoById(vo.getDarenUserId());
        List<SkYueDanOrderLogVo> list = skYueDanOrderLogMapper.getList(vo.getId());
        vo.setUserVo(userVo);
        vo.setDrUserVo(drUserVo);
        vo.setList(list);
        return vo;
    }

    /**
     * 近半年用户订单男女比例
     *
     * @return
     */
    @Override
    public Map<String, Object> getUserSexSumList() {
        Map<String, Object> map = new HashMap<>();
        List<SysSexSumReturn> list = baseMapper.getUserSexSumList();
        List<String> drNan = new ArrayList<>();
        List<String> drNv = new ArrayList<>();
        List<String> drNo = new ArrayList<>();
        List<String> Xzhou = new ArrayList<>();
        if (list.size() > 0) {
            for (SysSexSumReturn vo : list) {
                drNan.add(vo.getNan());
                drNv.add(vo.getNv());
                drNo.add(vo.getNos());
                Xzhou.add(vo.getTime());
            }
        }
        map.put("drNan", drNan);
        map.put("drNv", drNv);
        map.put("drNo", drNo);
        map.put("Xzhou", Xzhou);
        return map;
    }

    /**
     * 近半年达人订单男女比例
     *
     * @return
     */
    @Override
    public Map<String, Object> getDaRenSexSumList() {
        Map<String, Object> map = new HashMap<>();
        List<SysSexSumReturn> list = baseMapper.getDaRenSexSumList();
        List<String> drNan = new ArrayList<>();
        List<String> drNv = new ArrayList<>();
        List<String> drNo = new ArrayList<>();
        List<String> Xzhou = new ArrayList<>();
        if (list.size() > 0) {
            for (SysSexSumReturn vo : list) {
                drNan.add(vo.getNan());
                drNv.add(vo.getNv());
                drNo.add(vo.getNos());
                Xzhou.add(vo.getTime());
            }
        }
        map.put("drNan", drNan);
        map.put("drNv", drNv);
        map.put("drNo", drNo);
        map.put("Xzhou", Xzhou);
        return map;
    }

    /**
     * 约局订单时间到期后期处理
     *
     * @param
     */
    @Override
    public SkYueDanOrder daoqiOrderInfo(String orderId) {
        SkYueDanOrder order = baseMapper.selectById(orderId);
        //当订单为待接单时，超出开始时间，订单自动取消，并且退款
        if (order.getPayState().longValue() == 1) {
            if (order.getState().longValue() == 1) {
                order.setState(3L);
                baseMapper.updateById(order);
                iSkYueDanOrderLogService.createLog(order, "开始时间到期未接单系统自动取消", 5L);
                //退款  后期开发
            }
            if (order.getState().longValue() == 5) {
                order.setState(4L);
                baseMapper.updateById(order);
                iSkYueDanOrderLogService.createLog(order, "开始时间到期系统自动完成", 6L);
            }
        }
        return order;
    }

    @Override
    public SkYueDanOrder selectById(String orderId) {
        return baseMapper.selectById(orderId);
    }

    /**
     * 开始服务
     *
     * @param params
     * @param req
     */
    @Override
    public SkYueDanOrder getStartService(AppDetailByIdParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkYueDanOrder order = baseMapper.selectById(params.getId());
        if (userId.longValue() != order.getDarenUserId().longValue()){
            CssExceptionDescription.errorMsg(10026);
        }
        Date date = new Date();
        order.setStartFwTime(DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN));
        Date end = DateUtil.offset(date,DateField.HOUR,order.getLongTime().intValue());
        order.setEndFwTime(DateUtil.format(end,DatePattern.NORM_DATETIME_PATTERN));
        order.setState(5L);
        baseMapper.updateById(order);
        //类型 1:创建  2：转发  3：待接单  4：已接单  5：取消  6：完成 41:达人点击开始服务
        //添加log
        iSkYueDanOrderLogService.createLog(order, "达人点击开始服务", 41L);
        return order;
    }

    /**
     * 支付回调 后续处理
     * @param map
     */
    @Override
    public void getPaymentCallback(Map<String,String> map) {
        String orderId = map.get("out_trade_no");
        String wxTransactionId = map.get("transaction_id");
        SkYueDanOrder order = baseMapper.selectById(orderId.split("-")[1]);
        if (order.getPayState().longValue() == 0) {
            order.setPayState(1L);
            order.setPayTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
            order.setState(1L);
            order.setPayOrder(wxTransactionId);//三方支付订单号
            baseMapper.updateById(order);
            //经验值计算  start
            //自己在达人模块下单  增加经验值
            String obej = iBfExperienceLogService.getKeyValue("自己在达人模块下单");
            if (obej == null) {
                obej = "0";
            }
            Long userId = order.getUserId();
            iBfExperienceLogService.addLog(userId, obej, "自己在达人模块下单");
            //我的直推在达人模块下单 增加经验值
            SkAppUser user = skAppUserMapper.selectById(userId);
            if (user.getYqUserId() != null) {
                String obej2 = iBfExperienceLogService.getKeyValue("我的直推在达人模块下单");
                if (obej2 == null) {
                    obej2 = "0";
                }
                iBfExperienceLogService.addLog(user.getYqUserId(), obej2, "我的直推在达人模块下单");
            }
            //用户下单成功发送短信（给达人发）
            SkAppUser darenuser = skAppUserMapper.selectById(order.getDarenUserId());
            CssUtils.send(darenuser.getPhone(),"【尚客花街】温馨提示：您有新订单，用户："+user.getNickName()+"，于"+DateUtil.format(order.getCreateTime(),DatePattern.NORM_DATETIME_PATTERN)+"下单成功，请及时查看！");

        }


    }

    @Override
    public SkYueDanOrder getOrderById(String out_refund_no) {
        return baseMapper.selectById(out_refund_no);
    }

    @Override
    public void updateByInfo(SkYueDanOrder order) {
        baseMapper.updateById(order);
    }

    public void activeAccount(SkAppUser skAppUser, BigDecimal price, Long type, String content) {
        SkPriceLog sk = new SkPriceLog();
        sk.setPrice(price);
        sk.setUserId(skAppUser.getId());
        sk.setOldPrice(skAppUser.getPrice());
        sk.setType(type);
        sk.setTitle(content);
        skPriceLogMapper.insert(sk);
        skAppUserMapper.activePrice(skAppUser.getId(), price);
    }
}
